import { forwardRef, useImperativeHandle, useRef, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, Drawer, Form, FormProps, Input, Select, Space, Table, TreeSelect } from 'antd';
import { DataNode } from 'antd/es/tree';

import { store } from '@/store';

import { orgDeptInfoTreeList } from '@/services/base/bumenguanlibumenxiangguanjiekou';
import {
  equChangeScrappedAdd,
  equChangeScrappedGet,
  equChangeScrappedUpdate
} from '@/services/bizApi/shebaochuzhibaofeijiekou';
import { findIdByName } from '@/utils';

import { BizObject } from './';
import Device, { DeviceRef } from './device';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  const device = useRef<DeviceRef>(null);
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const [dataSource, setDataSource] = useState<BIZAPI.EquInfoEntity[]>([]);
  const treeDict = useRef<Record<number, DataNode>>({});
  const tree = useRequest(async () => {
    treeDict.current = {};

    const res = await orgDeptInfoTreeList();

    const formatData = (data: BASE.OrgDeptInfoVo[]): DataNode[] => {
      const result: DataNode[] = [];

      data.forEach((item) => {
        const node: DataNode = {
          title: item.deptName,
          key: item.id!,
          // @ts-ignore
          value: item.id!,
          children: []
        };

        treeDict.current[item.id!] = node;

        if (item.child && item.child.length > 0) {
          node.children = formatData(item.child);
        }

        result.push(node);
      });

      return result;
    };

    return formatData(res.data || []);
  });

  const equChangeScrapped = useRequest(
    async (id: string) => {
      const res = await equChangeScrappedGet({ id });
      const data = res?.data;
      // 回填数据
      form.setFieldsValue({
        ...res?.data
      });
      setDataSource((data?.detailList as unknown as BIZAPI.EquInfoEntity[]) || []);
    },
    {
      manual: true
    }
  );
  const submit = useRequest(
    async ({ _type, ...values }) => {
      if (!dataSource?.length) {
        store.app?.message.info('请添加详情');
        return;
      }
      const query = {
        ...values,
        manageDeptName: findIdByName(tree?.data || [], values?.manageDeptId as unknown as string),
        detailList: dataSource
      };

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit' ? equChangeScrappedUpdate(query) : equChangeScrappedAdd(query));

      args?.onSuccess?.();
      setOpen(false);
      setDataSource([]);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            equChangeScrapped.run(arg?.rowData?.id as unknown as string);
            // 回填数据
            // form.setFieldsValue({
            //   ...arg.rowData
            // });
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
    setDataSource([]);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增处置报废',
          edit: '编辑处置报废',
          detail: '处置报废详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="60%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="管理部门"
          name="manageDeptId"
          rules={[
            {
              required: true,
              message: '请选择管理部门'
            }
          ]}
        >
          <TreeSelect
            treeData={tree.data}
            treeNodeFilterProp="title"
            showSearch
            placeholder="请选择管理部门"
            allowClear
          />
        </Form.Item>
        <Form.Item
          label="报废名称"
          name="scrapName"
          rules={[
            {
              required: true,
              message: '请输入报废名称'
            }
          ]}
        >
          <Input placeholder="请输入报废名称" />
        </Form.Item>
        <Form.Item
          label="报废类型"
          name="scrapType"
          rules={[
            {
              required: true,
              message: '请选择报废类型'
            }
          ]}
        >
          <Select
            style={{
              width: '100%'
            }}
            allowClear
            placeholder="请选择报废类型"
            options={[
              {
                label: '盘亏',
                value: '盘亏'
              },
              {
                label: '损毁',
                value: '损毁'
              },
              {
                label: '达到最低使用年限',
                value: '达到最低使用年限'
              },
              {
                label: '其他',
                value: '其他'
              }
            ]}
          />
        </Form.Item>

        <Form.Item
          label="报损、报废原因"
          name="scrapReason"
          rules={[
            {
              required: false,
              message: '请输入报损、报废原因'
            }
          ]}
        >
          <Input.TextArea placeholder="请输入报损、报废原因" />
        </Form.Item>
        <Form.Item
          label="其他事项"
          name="remarks"
          rules={[
            {
              required: false,
              message: '请输入其他事项'
            }
          ]}
        >
          <Input.TextArea placeholder="请输入其他事项" />
        </Form.Item>
      </Form>
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          width: '100%',
          padding: '20px 24px 10px'
        }}
      >
        <div style={{ fontSize: '16px' }}>详情</div>
        <Button
          type="primary"
          disabled={args?.type === 'detail'}
          onClick={() => {
            if (!form.getFieldValue('manageDeptId')) {
              store.app?.message.info('请先选择管理部门');
              return;
            }
            device.current?.open({
              manageDeptId: form.getFieldValue('manageDeptId'),
              onSuccess: (rows) => {
                const arr = rows?.filter(
                  (item) => !dataSource?.some((itm) => itm?.id === item?.id)
                );
                setDataSource([...dataSource, ...arr]);
              }
            });
          }}
        >
          添加数据
        </Button>
      </div>

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: '资产编号',
            dataIndex: 'equipmentCode',
            align: 'center',
            width: 100
          },
          {
            title: '资产大类',
            dataIndex: 'equipmentType',
            align: 'center',
            width: 100
          },
          {
            title: '资产名称',
            dataIndex: 'equipmentName',
            align: 'center',
            width: 100
          },
          {
            title: '规格型号',
            dataIndex: 'specification',
            align: 'center',
            width: 100
          },
          {
            title: '生产站点',
            dataIndex: 'productionSite',
            align: 'center',
            width: 130
          },
          {
            title: '工艺段',
            dataIndex: 'processSection',
            align: 'center',
            width: 130
          },
          {
            title: '设备等级',
            dataIndex: 'equipmentLevel',
            align: 'center',
            width: 120
          },
          {
            title: '操作',
            fixed: 'right',
            width: 150,
            hidden: args?.type === 'detail',
            render: (text, record) => [
              <a
                key="delete"
                onClick={() => {
                  if (args?.type === 'detail') return;
                  setDataSource(dataSource.filter((item) => item.id !== record.id));
                }}
              >
                删除
              </a>
            ]
          }
        ]}
        dataSource={dataSource}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        // {...table.tableProps}
        pagination={
          {
            // ...table.tableProps.pagination,
            // showTotal: (total) => `共 ${total} 条`,
            // showQuickJumper: true,
            // showSizeChanger: true,
            // pageSizeOptions: ['10', '20', '50', '100']
          }
        }
      />
      {/* end表格 */}
      <Device ref={device} />
    </Drawer>
  );
};

export default forwardRef(Edit);
